package com.simou.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simou.common.CustomException;
import com.simou.common.R;
import com.simou.dao.CategoryMapper;
import com.simou.entity.Category;
import com.simou.entity.Dish;
import com.simou.entity.Setmeal;
import com.simou.service.CategoryService;
import com.simou.service.DishService;
import com.simou.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    DishService dishService;
    @Autowired
    SetmealService setmealService;

    @Override
    public void remove(Long id) {
        // 1.若分类关联了菜品，不能删除
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        if (dishService.count(dishLambdaQueryWrapper) > 0) {
//            写法一（不推荐，耦合性高，R.error不应该出现在service层）
//            return R.error("该分类关联了菜品,不能删除");
//            写法二：抛出自定义异常，全局的异常处理器会自动捕获并处理
            throw new CustomException("该分类关联了菜品,不能删除");
        }

        // 2.若分类关联了套餐，不能删除
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        if (setmealService.count(setmealLambdaQueryWrapper) > 0) {
//            写法一
//            return R.error("该分类关联了套餐");
            throw new CustomException("该分类关联了套餐,不能删除");
        }

        super.removeById(id);
    }
}
